<script setup lang="ts">
import { Check, Delete, Edit, Key, Message, Search, Star, } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { findByPage, getCompany, deleteMeter, addMeter, getMeter, updateMeter, getHost, getWareHouse, getMeterExcel } from '@/api/InstrumentManagement';
import { onMounted, reactive, ref } from 'vue';
import { id } from 'element-plus/es/locales.mjs';
import type { EnumType } from 'typescript';
// import { ComponentSize, FormInstance, FormRules } from 'element-plus'

//删除弹出框
const dele = (id: any) => {
  ElMessageBox.confirm(
    '确定要删除该企业?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(
      async () => {
        console.log(id);
        var { data: { code } } = await deleteMeter(id);
        //console.log(code);
        if (code == 200) {
          ElMessage({
            type: 'success',
            message: '删除成功',
          })
        } else {
          ElMessage({
            type: 'info',
            message: '删除失败',
          })
        }
        getInfo();
      })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除失败',
      })
    })
};


//分页参数信息

var state = reactive({
  tableData: [],
  company: [
    {
      id: 1,
      name: ""
    }
  ],
  warehouse: [
    {
      id: 1,
      name: "请先选择公司"
    }
  ],
  host: [
    {
      id: 1,
      name: "请先选择库房"
    }
  ],
  pageInfo: {
    pageNum: 1,
    pageSize: 10,
    companyName: ""
  },
  total: 0
})  

//分页相关函数
// const getPage = (newPage: any) => {
//   state.pageInfo.pageNum = newPage;
//   getInfo();
//   //console.log(`当前页码已变更为: ${newPage}`);
// };

// const currentPage4 = ref(1)
// const pageSize4 = ref(1)
const small = ref(false)
const background = ref(false)
const disabled = ref(false)

const handleSizeChange = (val: number) => {
  state.pageInfo.pageSize = val;
  getInfo();
}
const handleCurrentChange = (val: number) => {
  state.pageInfo.pageNum = val;
  getInfo();
}


// 请求方法
async function getInfo() {
  try {
    const response = await findByPage(state.pageInfo)
    if (response.data && response.data.data) {
      state.tableData = response.data.data.rows
      state.total = response.data.data.total
    } else {
      console.error('返回数据格式不正确:', response)
      ElMessage({
        type: 'error',
        message: '获取数据失败'
      })
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage({
      type: 'error',
      message: '获取数据失败'
    })
  }
}

//新增二级弹窗
const dialogAddFormVisible = ref(false)

interface RuleForm {
  id: string,
  sn: string,
  name: string,
  hostId: string,
  maxHum: string,
  minHum: string,
  maxTem: string,
  minTem: string,
  collectInterval: string,
  state: string,
  remark: string,
  companyId: string,
  warehouseId: string,
  token: string,
  type: number
}
const addFormRef = ref<FormInstance>()
const addForm = reactive<RuleForm>({
  id: '',
  sn: '',
  name: '',
  hostId: '',
  maxHum: '',
  minHum: '',
  maxTem: '',
  minTem: '',
  collectInterval: '',
  state: '',
  remark: '',
  companyId: '',
  warehouseId: '',
  token: "",
  type: 0
})
// 新增部分
const radio3 = ref('0')
const rules = reactive<FormRules<RuleForm>>({
  sn: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  name: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  hostId: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  maxHum: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  minHum: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  maxTem: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  minTem: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  collectInterval: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  state: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  remark: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  companyId: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  warehouseId: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  token: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ],
  type: [
    {
      required: true,
      message: 'Please select Activity zone',
      trigger: 'blur',
    },
  ]
})

//添加  
const resetAddForm = (formEl: FormInstance | undefined) => {
  dialogAddFormVisible.value = false
  if (!formEl) return
  formEl.resetFields()
}

// 生成仪表编号的函数
function generateSn() {
  const timestamp = new Date().getTime();
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  return `M${timestamp}${random}`;
}

async function addFormVisible(){
  dialogAddFormVisible.value = true;
  // 自动生成sn
  addForm.sn = generateSn();
  var {data:{data}} = await getCompany();
  state.company = data;
}

const submitAddForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //console.log('submit!')
      addMeters();
      dialogAddFormVisible.value = false
      formEl.resetFields();
    } else {
      //console.log('error submit!', fields)
    }
  })
}

async function addMeters() {
  var { data: { code } } = await addMeter(addForm);
  //console.log(code);
  if (code == 200) {
    ElMessage({
      type: 'success',
      message: '添加成功',
    })
  } else {
    ElMessage({
      type: 'info',
      message: '添加失败',
    })
  }
  getInfo();
}

//修改
const dialogUpdateFormVisible = ref(false)
const updateFormRef = ref<FormInstance>()

interface RuleFormup {
  id: string,
  name: string,
  hostId: string,
  state: string,
  remark: string,
  companyId: string,
  warehouseId: string
}
var updateForm = reactive<RuleFormup>({
  id: '',
  name: '',
  hostId: '',
  state: '',
  remark: '',
  companyId: '',
  warehouseId: ''
})

const resetUpdateForm = (formEl: FormInstance | undefined) => {
  dialogUpdateFormVisible.value = false
  if (!formEl) return
  formEl.resetFields()
}
async function updateFormVisible(id: any) {
  var meterData = await getMeter(id);
  Object.assign(updateForm, meterData.data.data);
  //updateForm = meterData.data.data;
  console.log(updateForm);
  var { data: { data } } = await getCompany();
  //console.log(data);
  state.company = data;
  //console.log(state.company);
  upfindWareHouseByCompanyId()
  upfindHostByWareHouseId();
  dialogUpdateFormVisible.value = true;
}

const submitUpdateForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      //console.log('submit!')
      updateMeters();
      dialogUpdateFormVisible.value = false
      formEl.resetFields();
    } else {
      //console.log('error submit!', fields)
    }
  })
}

async function updateMeters() {
  var { data: { code } } = await updateMeter(updateForm);
  //console.log(code);
  if (code == 200) {
    ElMessage({
      type: 'success',
      message: '修改成功',
    })
  } else {
    ElMessage({
      type: 'info',
      message: '修改失败',
    })
  }
  getInfo();
}

async function findByCompany() {
  console.log(state.pageInfo.companyName);
  getInfo()
}

async function addfindWareHouseByCompanyId() {
  var { data } = await getWareHouse(addForm.companyId);
  state.warehouse = data.data;
}

async function addfindHostByWareHouseId() {
  var { data } = await getHost(addForm.warehouseId);
  state.host = data.data;
}

async function upfindWareHouseByCompanyId() {
  var { data } = await getWareHouse(updateForm.companyId);
  state.warehouse = data.data;
}
async function upfindHostByWareHouseId() {
  var { data } = await getHost(updateForm.warehouseId);
  state.host = data.data;
}
const handleDownload = async () => {

  try {
    const response = await getMeterExcel();

    // 创建隐藏的可下载链接
    const link = document.createElement('a');
    const url = URL.createObjectURL(new Blob([response.data]));
    link.href = url;
    link.setAttribute('download', '仪表信息表.xlsx'); // 设置下载文件名
    document.body.appendChild(link);
    link.click(); // 触发下载
    link.remove(); // 下载完成后移除元素
    URL.revokeObjectURL(url); // 释放掉该对象url

    // 可选：显示成功消息
    ElMessage.success('下载成功！');
  } catch (error) {
    console.error('There was an error fetching the Excel file!', error);
    ElMessage.error('下载失败，请稍后再试！');
  }
};

// 挂载函数
onMounted(() => {
  getInfo();
});

</script>

<template>
  <!-- 搜索框 -->
  <el-input class="input" style="width: 240px" placeholder="请输入企业名称" v-model="state.pageInfo.companyName"
    @blur="findByCompany" />

  <!-- 新增按钮 -->
  <div class="mb-4">
    <el-button plain @click="addFormVisible">+新增</el-button>
  </div>

  <div class="mb-4">
    <el-button plain @click="handleDownload()" type="success">打印表格</el-button>
  </div>
  <!-- 信息表格 -->
  <el-table :data="state.tableData" style="width: 100%">
    <el-table-column prop="id" label="ID" align="center" />
    <el-table-column prop="companyName" label="企业名称" align="center" />
    <el-table-column prop="hostName" label="主机名称" align="center" />
    <el-table-column prop="sn" label="仪表编号" align="center" />
    <el-table-column prop="name" label="仪表名称" align="center" />
    <el-table-column prop="warehouseName" label="所在库房" align="center" />
    <el-table-column label="温度阈值" align="center">
      <template v-slot="scope">
        {{ scope.row.minTem }} / {{ scope.row.maxTem }}
      </template>
    </el-table-column>
    <el-table-column label="湿度阈值" align="center">
      <template v-slot="scope">
        {{ scope.row.minHum }} / {{ scope.row.maxHum }}
      </template>
    </el-table-column>
    <el-table-column label="采集间隔" align="center">
      <template v-slot="scope">
        {{ scope.row.collectInterval }}s
      </template>
    </el-table-column>
    <el-table-column prop="state" label="状态" align="center">
      <template v-slot="scope">
        <span v-if="scope.row.state === 0">启用</span>
        <span v-else-if="scope.row.state === 1">停用</span>
        <span v-else-if="scope.row.state === 2">异常</span>
        <span v-else>未知</span>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="center" width="200">
      <!-- scope.row 表示当前行的数据 -->
      <template v-slot="scope">
        <!-- <a href="javascript:void(0)" @click="dele(scope.row.id)">删除</a> -->
        <el-button type="warning" :icon="Edit" @click="updateFormVisible(scope.row.id)">
          修改</el-button>
        <el-button type="danger" :icon="Delete" @click="dele(scope.row.id)">
          删除</el-button>
        <!-- <a href="javascript:void(0)" @click="updateFormVisible(scope.row.id)">修改</a> -->
      </template>

    </el-table-column>
  </el-table>

  <!-- 分页部分 -->
  <div class="example-pagination-block">
    <!-- <el-pagination background layout="prev, pager, next" :total="state.total" @current-change="getPage"
      v-model:current-page="state.pageInfo.pageNum" /> -->
    <el-pagination v-model:current-page="state.pageInfo.pageNum" v-model:page-size="state.pageInfo.pageSize"
      :page-sizes="[5, 10, 15, 20]" :small="small" :disabled="disabled" :background="background"
      layout="total, sizes, prev, pager, next, jumper" :total="state.total" @size-change="handleSizeChange"
      @current-change="handleCurrentChange" />
  </div>

  <!-- 新增弹出框 -->
  <el-dialog v-model="dialogAddFormVisible" title="新增仪表" width="800px">
    <el-form ref="addFormRef" :inline="true" :model="addForm" :rules="rules" class="demo-form-inline"
      style="margin-left: 10%;margin-top: 20px;">

        <el-form-item label="企业名称:" prop="companyId">
          <el-select
            v-model="addForm.companyId"
            placeholder="请选择企业"
            clearable
            @change="addfindWareHouseByCompanyId()"
          >
            <el-option v-for="item in state.company"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
            
          </el-select>
        </el-form-item>


        <el-form-item label="库房名称:" prop="warehouseId">
          <el-select
            v-model="addForm.warehouseId"
            placeholder="请选择库房"
            clearable
            @change="addfindHostByWareHouseId()"
          >
          <el-option v-for="item in state.warehouse"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="管理主机:" prop="hostId">
          <el-select
            v-model="addForm.hostId"
            placeholder="请选择管理主机"
            clearable
          >
          <el-option v-for="item in state.host"
            :key="item.id"
            :label="item.name"
            :value="item.id"/>
          </el-select>
        </el-form-item>

        <el-form-item label="仪表名称:" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入仪表名称" clearable />
        </el-form-item>

        <el-form-item label="仪表编号:" prop="sn">
          <el-input v-model="addForm.sn" placeholder="仪表编号" readonly />
        </el-form-item>

        <el-form-item label="仪表状态:" prop="state">
          <el-select
            v-model="addForm.state"
            placeholder="请选择仪表状态"
            clearable
          >
            <el-option label="在用" value="0" />
            <el-option label="停用" value="1" />
            <el-option label="异常" value="2" />
          </el-select>
        </el-form-item>

        <el-form-item label="温度上限:" prop="maxTem">
          <el-input v-model="addForm.maxTem" placeholder="请输入温度上限" clearable />
        </el-form-item>

        <el-form-item label="温度下限:" prop="minTem">
          <el-input v-model="addForm.minTem" placeholder="请输入温度下限" clearable />
        </el-form-item>

        <el-form-item label="湿度上限:" prop="maxHum">
          <el-input v-model="addForm.maxHum" placeholder="请输入湿度上限" clearable />
        </el-form-item>

        <el-form-item label="湿度下限:" prop="minHum">
          <el-input v-model="addForm.minHum" placeholder="请输入湿度下限" clearable />
        </el-form-item>

        <el-form-item label="采集间隔:" prop="collectInterval">
          <el-input v-model="addForm.collectInterval" placeholder="请输入采集间隔" clearable />
        </el-form-item>

        <el-form-item label="备注信息:" prop="remark">
          <el-input v-model="addForm.remark" placeholder="请输入备注信息" clearable />
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetAddForm(addFormRef)">取消</el-button>
          <el-button type="primary" @click="submitAddForm(addFormRef)">
            确认
          </el-button>
        </div>
      </template>
      
    </el-dialog>


    <!-- 修改弹出框 -->
    <el-dialog v-model="dialogUpdateFormVisible" title="修改仪表" width="800px">
      <el-form 
      ref="updateFormRef"
      :inline="true" 
      :model="updateForm"
      :rules="rules" 
      class="demo-form-inline" 
      style="margin-left: 10%;margin-top: 20px;">

      <el-form-item label="企业名称:" prop="companyId">
        <el-select v-model="updateForm.companyId" placeholder="请选择企业" clearable @change="upfindWareHouseByCompanyId()">
          <el-option v-for="item in state.company" :key="item.id" :label="item.name" :value="item.id" />

        </el-select>
      </el-form-item>


      <el-form-item label="库房名称:" prop="warehouseId">
        <el-select v-model="updateForm.warehouseId" placeholder="请选择库房" clearable @change="upfindHostByWareHouseId()">
          <el-option v-for="item in state.warehouse" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="管理主机:" prop="hostId">
        <el-select v-model="updateForm.hostId" placeholder="请选择管理主机" clearable>
          <el-option v-for="item in state.host" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="仪表名称:" prop="name">
        <el-input v-model="updateForm.name" placeholder="请输入仪表名称" clearable />
      </el-form-item>

      <!-- <el-form-item label="仪表编号:" prop="sn">
        <el-input v-model="updateForm.sn" placeholder="请输入仪表编号" clearable />
      </el-form-item> -->

      <el-form-item label="仪表状态:" prop="state">
        <el-select v-model="updateForm.state" placeholder="请选择仪表状态" clearable>
          <el-option label="在用" :value="0" />
          <el-option label="停用" :value="1" />
          <el-option label="异常" :value="2" />
        </el-select>
      </el-form-item>

      <!-- <el-form-item label="温度上限:" prop="maxTem">
        <el-input v-model="updateForm.maxTem" placeholder="请输入温度上限" clearable />
      </el-form-item>

      <el-form-item label="温度下限:" prop="minTem">
        <el-input v-model="updateForm.minTem" placeholder="请输入温度下限" clearable />
      </el-form-item>

      <el-form-item label="湿度上限:" prop="maxHum">
        <el-input v-model="updateForm.maxHum" placeholder="请输入湿度上限" clearable />
      </el-form-item>

      <el-form-item label="湿度下限:" prop="minHum">
        <el-input v-model="updateForm.minHum" placeholder="请输入湿度下限" clearable />
      </el-form-item> -->

      <!-- <el-form-item label="采集间隔:" prop="collectInterval">
        <el-input v-model="updateForm.collectInterval" placeholder="请输入采集间隔" clearable />
      </el-form-item> -->

      <el-form-item label="备注信息:" prop="remark">
        <el-input v-model="updateForm.remark" placeholder="请输入备注信息" clearable />
      </el-form-item>

    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="resetUpdateForm(updateFormRef)">取消</el-button>
        <el-button type="primary" @click="submitUpdateForm(updateFormRef)">
          确认
        </el-button>
      </div>
    </template>

  </el-dialog>


</template>

<style scoped>
/* 分页样式 */
.example-pagination-block {
  margin-top: 10px;
  float: right;
}

.demo-pagination-block+.demo-pagination-block {
  margin-top: 10px;
}

.demo-pagination-block .demonstration {
  margin-bottom: 16px;
}

a {
  color: blue;
  margin-left: 7px;
  font-size: 17px;
}

.mb-4 {
  display: inline-block;
  margin: 5px;
  float: right;
}

.input {
  display: inline-block;
  margin: 5px;
  float: right;
}


.example-pagination-block+.example-pagination-block {
  margin-top: 10px;
}

.example-pagination-block .example-demonstration {
  margin-bottom: 16px;
}

.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>